package inet.app.view.fragment;

import inet.app.R;
import inet.app.controller.connect.MasterConnector;
import inet.app.controller.parser.Parser_Cau;
import inet.app.controller.parser.Parser_Kq_Cau;
import inet.app.controller.request.Request_Format;
import inet.app.model.cau.CauCell;
import inet.app.model.cau.CauTable;
import inet.app.model.cau.CauVT;
import inet.app.model.cau.Giai;
import inet.app.model.cau.Global;
import inet.app.model.cau.KetQua;
import inet.app.model.cau.UnderlinedClickableSpan;
import inet.app.model.util.ControllableProgressDialog;
import inet.app.model.util.DateProc;
import inet.app.model.util.MyPreferenceManager;
import inet.app.model.util.ProgressDialog;
import inet.app.model.util.TimeConsummingTaskInterface;
import inet.app.model.util.Util;
import inet.app.view.activity.CauNgayDetail;
import inet.app.view.activity.MyApp;
import inet.app.view.dialog.LoginDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class FragmentVipCauNgay extends BaseFragmentTV implements
		OnClickListener, OnTouchListener {
	private String response;
	ArrayList<String> list = new ArrayList<String>();
	private ProgressDialog pdia;
	private TextView tvSpTinh;
	private int myYear, myMonth, myDay, myHour, myMinute;
	private TableLayout tableCau;
	private String[] list_tentinhMB = new String[] { "Thủ Đô"};
	
	private String[] list_tentinhMT = new String[] { "Bình Định", "Đắk Lắk", "Gia Lai", "Khánh Hòa", "Kon Tum",
			"Ninh Thuận", "Phú Yên", "Quảng Bình", "Quảng Nam", "Quảng Ngãi",
			"Quảng Trị", "Thừa Thiên Huế", "Đà Nẵng", "Đắc Nông" };
	
	private String[] list_tentinhMN = new String[] { "TP HCM",
			"An Giang", "Bình Dương", "Bình Phước", "Bạc Liêu", "Bến Tre",
			"Cà Mau", "Cần Thơ", "Hậu Giang", "Kiên Giang", "Long An",
			"Sóc Trăng", "Tiền Giang", "Trà Vinh", "Tây Ninh", "Vĩnh Long",
			"Vũng Tàu", "Đà Lạt", "Đồng Nai", "Đồng Tháp", "Bình Thuận"};
	
	private MasterConnector master;
	private Spinner spTinh;
	private String code = "XSTD", name = "Thủ Đô", date_current;
	private int biendo = 5;
	private Button btXemKetQua;
	private EditText etDate, etBiendo;
	private TextView tvfotter;
	// CẦU
	static public CauTable cauTable;
	static public KetQua ketQua;// da co ket qua hom nay
	static public ArrayList<CauVT> posList;// cau VT
	public static int bienDoCauDefault = 5;

	public static Fragment newInstance(Context context) {
		FragmentVipCauNgay f = new FragmentVipCauNgay();
		return f;
	}

	public static Fragment newInstance(Context context, String position) {
		FragmentVipCauNgay f = new FragmentVipCauNgay();
		Bundle args = new Bundle();
		args.putString("pos", position);
		f.setArguments(args);
		return f;
	}

	public static Fragment newInstance(Context context, String position,String json) {
		System.out.println("RUn here ==== ...>>");
		FragmentVipCauNgay f = new FragmentVipCauNgay();
		Bundle args = new Bundle();
		args.putString("pos", position);
		args.putString("json", json);
		f.setArguments(args);
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(
				R.layout.fragment_vip_caungay, null);
		// Khởi tạo master
		pdia = new ProgressDialog(getActivity());

		tvfotter = (TextView) root.findViewById(R.id.tvfotter);
		etDate = (EditText) root.findViewById(R.id.etDate);
		etBiendo = (EditText) root.findViewById(R.id.etBiendo);
		tvSpTinh = (TextView) root.findViewById(R.id.tvSpTinh);
		spTinh = (Spinner) root.findViewById(R.id.sptinh);
		btXemKetQua = (Button) root.findViewById(R.id.btXemKetQua);
		tableCau = (TableLayout) root.findViewById(R.id.tableLayout);
		// REMOVE
		tableCau.removeAllViews();

		date_current = DateProc.Timestamp2DDMMYYYY(DateProc.createTimestamp());
		// Set day, month, year
		myYear = Integer.parseInt(date_current.split("/")[2]);
		myMonth = Integer.parseInt(date_current.split("/")[1]);
		myDay = Integer.parseInt(date_current.split("/")[0]);
		etDate.setText(date_current);
		AddSpinnerMB();
		implementUI();
		// --------------------------------THONG KE CẦU ---------------
		tableCau.setStretchAllColumns(true);
		tableCau.setShrinkAllColumns(true);
		ketQua=null; posList=null;
		// if(ketQua!=null && posList!=null)
		// initTableCau();
		return root;
	}

	private void initTableCau() {
		// TODO Auto-generated method stub
		if (posList != null)
			cauTable = getCauTable();
		tableCau.removeAllViews();
		for (int i = 0; i < 10; i++) {
			createRow(i);
		}

	}

	private CauTable getCauTable() {
		CauTable tb = new CauTable();
		for (CauVT cau : posList) {
			CauCell cell = getCell(cau);
			tb.addCell(cell);
		}
		return tb;
	}

	private CauCell getCell(CauVT cau) {
		int i, j;
		if (code.equals("XSTD")) {
			Global.mien = 1;
			i = ketQua.getValueAtPos(cau.vt1);
			j = ketQua.getValueAtPos(cau.vt2);
		} else {
			Global.mien = 3;
			i = ketQua.getValueAtPosMN6so(cau.vt1);
			j = ketQua.getValueAtPosMN6so(cau.vt2);
		}
		return new CauCell(10 * i + j, cau.vt1, cau.vt2);
	}

	private void createRow(int i) {
		TableRow row = new TableRow(mActivity);
		row.setGravity(Gravity.CENTER);
		row.setPadding(0, 10, 0, 0);

		TextView head = new TextView(mActivity);
		head.setGravity(Gravity.CENTER_HORIZONTAL);
		head.setText("Đầu " + i + ":");
		head.setTextColor(Color.BLACK);
		row.addView(head);

		// CauRow cauRow = new CauRow(row);
		for (int j = 0; j < 10; j++) {
			TextView tv = new TextView(mActivity);
			tv.setGravity(Gravity.CENTER_HORIZONTAL);
			int cauVal = i * 10 + j;
			CauCell cell = cauTable.getCell(cauVal);
			if (cell != null) {
				String cauValStr = cell.getValueStr();
				SpannableStringBuilder spanStr = makeLink(cauValStr);
				tv.setText(spanStr);
				tv.setMovementMethod(LinkMovementMethod.getInstance());
			}
			row.addView(tv);

		}
		tableCau.addView(row);
	}

	private void implementUI() {
		// Load animation
		final Animation text_animation = AnimationUtils.loadAnimation(
				getActivity(), R.anim.custom_text_animation);
		tvfotter.startAnimation(text_animation);
		tvfotter.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pdia.show();
				Intent myWebLink = new Intent(
						android.content.Intent.ACTION_VIEW);
				myWebLink.setData(Uri.parse("http://m.ole.vn/"));
				pdia.dismiss();
				startActivity(myWebLink);
			}
		});

		tvSpTinh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				spTinh.performClick();
			}
		});
		etBiendo.setOnTouchListener(FragmentVipCauNgay.this);
		etDate.setOnTouchListener(FragmentVipCauNgay.this);
		btXemKetQua.setOnClickListener(FragmentVipCauNgay.this);
	}

	public void viewResult() {
		String bdc = etBiendo.getText().toString();
		if (bdc != null && !bdc.trim().equals("")) {
			ControllableProgressDialog pDialog = new ControllableProgressDialog(
					getActivity(), soicauRequest, getResources().getString(
							R.string.notice), "Đang kết nối...");
			pDialog.run();
		}
	}

	TimeConsummingTaskInterface soicauRequest = new TimeConsummingTaskInterface() {
		@Override
		public void updateGUI() {
			if (posList != null && ketQua != null) {
				initTableCau();
			} else {
				tableCau.removeAllViews();
				Util.showDialog(8, getActivity());
			}
		}

		@Override
		public void runTask() {
			master = new MasterConnector(((MyApp) mApplication).getIp(),
					((MyApp) mApplication).getPort());
			int delay = 0;
			int waitTime = 1000;
			// ------------------------------------Request
			// Cầu--------------------------------------------
			biendo = Integer.parseInt(etBiendo.getText().toString());
			date_current = etDate.getText().toString();
			posList = getSoiCau(((MyApp) mApplication).getAppid(),
					date_current, code, biendo);
			Util.sleep(waitTime);
			delay += waitTime;
			System.out.println("RUN 1=========>>");
			// -------------------------------------Request Kết
			// Quả-------------------------------------------
			if (posList != null) {
				System.out.println("RUN 2=========>>");
				ketQua = getKetQua(date_current,
						((MyApp) mApplication).getAppid(), code, biendo);
			}
		}
	};

	public ArrayList<CauVT> getSoiCau(final String App_id,
			final String ngaySoi, final String code, final int biendo) {
		System.out.println("==============>> RUN GET SOI CAU ");
		((MyApp) mApplication).set_socket(master.get_socket());
		master.stopConn2Master();
		String _result = master.getRequest_Cau(Request_Format.Tk_Cau_Req(App_id, ngaySoi, code, biendo));
		Parser_Cau parser_Cau = new Parser_Cau();

		if (_result != null && !_result.equals("")) {
			_result = parser_Cau.getString(_result);
			_result = Util.replaceAll(_result, " ", "");
			_result = Util.replaceAll(_result, "\n", "").trim();
			if (_result.startsWith("")) {
				String[] StringCauTable = _result.split("\\|");
				if (StringCauTable.length > 0) {
					ArrayList<CauVT> cauVTList = new ArrayList<CauVT>();
					for (int i = 5; i < StringCauTable.length; i++) {
						String[] StringCau = StringCauTable[i].split(":");
						if (StringCauTable.length > 1) {
							int pos1 = Integer.valueOf(StringCau[0]);
							int pos2 = Integer.valueOf(StringCau[1]);
							CauVT cauVT = new CauVT(pos1, pos2);
							cauVTList.add(cauVT);
						}
					}
					return cauVTList;
				}
			}
		}
		return null;
	}

	public KetQua getKetQua(String ngayTuongThuat, String App_id, String code,
			int soketqua) {
		System.out.println("==============>> RUN KET QUA ");
		response = master.getRequest_Cau(Request_Format.Xs_Cau_Req(App_id,
				code, soketqua));
		String _result = null;
		Parser_Kq_Cau parser_Xssc = new Parser_Kq_Cau();
		response = parser_Xssc.getString(response);

		if (response != null) {
			list = parser_Xssc.getList(response);
			_result = list.get(0);
		}
		if (_result != null && !_result.equals("")) {
			_result = Util.replaceAll(_result, " ", "");
			_result = Util.replaceAll(_result, "\n", "").trim();
			if (_result.startsWith("XS_CAU_RESP")) {
				ArrayList<Giai> Giais = new ArrayList<Giai>();
				String[] Stringgiais = _result.split("\\|");
				for (int i = 5; i < Stringgiais.length; i++) {
					if (Stringgiais[i].trim()
							.substring(2, Stringgiais[i].trim().length())
							.contains("null"))
						continue;
					Giai giai = null;
					ArrayList<String> resultList = new ArrayList<String>();

					if (Stringgiais[i].trim()
							.substring(2, Stringgiais[i].trim().length())
							.equals("-")) {
						giai = new Giai(resultList);
					} else {
						String[] kg = Stringgiais[i].substring(2,
								Stringgiais[i].trim().length()).split("-");
						for (int j = 0; j < kg.length; j++) {
							resultList.add(kg[j].trim());
						}
						giai = new Giai(resultList);
					}

					Giais.add(giai);
				}

				KetQua ketQua = new KetQua(Giais, ngayTuongThuat);
				return ketQua;
			}
		}
		return null;
	}

	private SpannableStringBuilder makeLink(String text) {
		SpannableStringBuilder spanable = Util.makeLink(text, goToCauDetail,
				Color.BLUE, Typeface.NORMAL);
		return spanable;
	}

	UnderlinedClickableSpan goToCauDetail = new UnderlinedClickableSpan() {
		@Override
		public void onClick(View widget) {
			System.out.println("MACKE LINK 22222 ");
			Intent intent = new Intent(getActivity(), CauNgayDetail.class);
			TextView tv = (TextView) widget;
			int num = Integer.parseInt(tv.getText().toString());
			if (etBiendo.getText() != null
					&& !etBiendo.getText().toString().trim().equals("")) {
				System.out.println("Click to number:" + num);
				int value = Integer.parseInt(etBiendo.getText().toString());
				intent.putExtra("biendo", value);
				intent.putExtra("code", code);
				intent.putExtra("tentinh", name);
				intent.putExtra("response", response);
				intent.putStringArrayListExtra("list", list);
			} else {
				intent.putExtra("biendo", 1);
			}
			CauCell cell = cauTable.getCell(num);
			CauNgayDetail.cauCell = cell;
			CauNgayDetail.ketQuaList = new ArrayList<KetQua>();
			CauNgayDetail.ketQuaList.add(ketQua);
			intent.putExtra("cauNumber", num);
			startActivity(intent);
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btXemKetQua:
			hideSoftKeyboard(etBiendo);
			if (MyPreferenceManager.getInstance(getActivity()).getMember()!=null) 
				viewResult();
			else{
				LoginDialog
				.newInstance(mActivity)
				.setLoginListener(mActivity.mLoginListener)
				.show(mActivity
						.getSupportFragmentManager(),
						"login_dialog");
				pdia.dismiss();
			}
//				Util.showDialog("Bạn chưa đăng nhập, Mời đăng nhập để sử dụng tính năng này !", getActivity());
			break;
		default:
			break;
		}
	}

	protected void hideSoftKeyboard(EditText input) {
		input.setInputType(0);
		InputMethodManager imm = (InputMethodManager) getActivity()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(input.getWindowToken(), 0);

	}

	protected void showSoftKeyboard(EditText input) {
		input.setInputType(0);
		InputMethodManager imm = (InputMethodManager) getActivity()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		// imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
		imm.showSoftInput(getActivity().getCurrentFocus(),
				InputMethodManager.SHOW_FORCED);

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN)
			switch (v.getId()) {
			case R.id.etDate:
				DatePickerDialog.OnDateSetListener myOnDateListener = new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						myYear = year;
						myMonth = monthOfYear + 1;
						myDay = dayOfMonth;
						// FORMAT DATE
						SimpleDateFormat form1 = new SimpleDateFormat(
								"dd/MM/yyyy");
						java.sql.Timestamp ts1 = DateProc.buildTimestamp(
								myYear, myMonth, myDay);
						date_current = form1.format(ts1);
						// END
						etDate.setText(date_current);
						// sendRequestList(date_current);
					}
				};
				DatePickerDialog datepicker = new DatePickerDialog(mActivity,
						myOnDateListener, myYear, myMonth - 1, myDay);
				datepicker.show();
				break;
			case R.id.etBiendo:
				showSoftKeyboard(etBiendo);
				etBiendo.setInputType(InputType.TYPE_CLASS_NUMBER);
				break;
			default:
				break;
			}
		return false;
	}
	
	public void loadSpinner(String tenMien) {
		tableCau.removeAllViews();
		if(tenMien.contains("Miền Bắc")){
			AddSpinnerMB();
		}else if (tenMien.contains("Miền Trung")) {
			AddSpinnerMT();
		}else if (tenMien.contains("Miền Nam")) {
			AddSpinnerMN();
		}
	}
	private void AddSpinnerMB() {
		ArrayAdapter<String> arrayadapter_sptinh = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item,
				list_tentinhMB);
		arrayadapter_sptinh
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTinh.setAdapter(arrayadapter_sptinh);
		spTinh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View v,
					final int pos, long id) {
				tvSpTinh.setText(" " + list_tentinhMB[pos]);
				spTinh.setSelection(pos);
				tableCau.removeAllViews();
				switch (pos) {
				case 0:
					name = "Thủ Đô";
					code = "XSTD";
					break;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}
	private void AddSpinnerMT() {
		ArrayAdapter<String> arrayadapter_sptinh = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item,
				list_tentinhMT);
		arrayadapter_sptinh
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTinh.setAdapter(arrayadapter_sptinh);
		spTinh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View v,
					final int pos, long id) {
				tvSpTinh.setText(" " + list_tentinhMT[pos]);
				spTinh.setSelection(pos);
				tableCau.removeAllViews();
				switch (pos) {
				case 0:
					code = "XSBDH";
					name = "Bình Định";
					break;
				case 1:
					code = "XSDLK";
					name = "Đăk Lăk";
					break;
				case 2:
					code = "XSGL";
					name = "Gia Lai";
					break;
				case 3:
					code = "XSKH";
					name = "Khánh Hòa";
					break;
				case 4:
					code = "XSKT";
					name = "Kon Tum";
					break;
				case 5:
					code = "XSNT";
					name = "Ninh Thuận";
					break;
				case 6:
					code = "XSPY";
					name = "Phú Yên";
					break;
				case 7:
					code = "XSQB";
					name = "Quảng Bình";
					break;
				case 8:
					code = "XSQNM";
					name = "Quảng Nam";
					break;
				case 9:
					code = "XSQNI";
					name = "Quảng Ngãi";
					break;
				case 10:
					code = "XSQT";
					name = "Quảng Trị";
					break;
				case 11:
					code = "XSTTH";
					name = "Thừa Thiên Huế";
					break;
				case 12:
					code = "XSDNG";
					name = "Đà Nẵng";
					break;
				case 13:
					code = "XSDNO";
					name = "Đắc Nông";
					break;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}
	private void AddSpinnerMN() {
		ArrayAdapter<String> arrayadapter_sptinh = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item,
				list_tentinhMN);
		arrayadapter_sptinh
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTinh.setAdapter(arrayadapter_sptinh);
		spTinh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View v,
					final int pos, long id) {
				tvSpTinh.setText(" " + list_tentinhMN[pos]);
				spTinh.setSelection(pos);
				tableCau.removeAllViews();
				switch (pos) {
				case 0:
					name = "TP HCM";
					code = "XSHCM";
					break;
				case 1:
					code = "XSAG";
					name = "An Giang";
					break;
				case 2:
					code = "XSBD";
					name = "Bình Dương";
					break;
				case 3:
					code = "XSBP";
					name = "Bình Phước";
					break;
				case 4:
					code = "XSBL";
					name = "Bạc Liêu";
					break;
				case 5:
					code = "XSBT";
					name = "Bến Tre";
					break;
				case 6:
					code = "XSCM";
					name = "Cà Mau";
					break;
				case 7:
					code = "XSCT";
					name = "Cần Thơ";
					break;
				case 8:
					code = "XSHG";
					name = "Hậu Giang";
					break;
				case 9:
					code = "XSKG";
					name = "Kiên Giang";
					break;
				case 10:
					code = "XSLA";
					name = "Long An";
					break;
				case 11:
					code = "XSST";
					name = "Sóc Trăng";
					break;
				case 12:
					code = "XSTG";
					name = "Tiền Giang";
					break;
				case 13:
					code = "XSTV";
					name = "Trà Vinh";
					break;
				case 14:
					code = "XSTN";
					name = "Tây Ninh";
					break;
				case 15:
					code = "XSVL";
					name = "Vĩnh Long";
					break;
				case 16:
					code = "XSVT";
					name = "Vũng Tàu";
					break;
				case 17:
					code = "XSDL";
					name = "Đà Lạt";
					break;
				case 18:
					code = "XSDN";
					name = "Đông Nai";
					break;
				case 19:
					code = "XSDT";
					name = "Đồng Tháp";
					break;
				case 20:
					code = "XSBTH";
					name = "Bình Thuận";
					break;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}
	public String sendrequestCAU(final String App_id,final String ngaySoi) {
		pdia.show();
		AsyncTask<String, Integer, String> myTask = new AsyncTask<String, Integer, String>() {

			protected void onPostExecute(Void result) {
				super.onPreExecute();
			}
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				return master.getRequest_Cau(Request_Format.Tk_Cau_Req(App_id, ngaySoi, code, biendo)).toString();
			}
		};
		myTask.execute();
		return null;
	}

}
